<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Db;
use \think\model\relation\HasMany;

class Business extends Base
{

    public function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,account,code,nickname,mobile,password');
    }

    public function getCate1TextAttr($value, $data)
    {
        return $data['cate_1'] ? ProductCate::whereIn('id', $data['cate_1'])->column('title') : '';
    }

    public function products(): HasMany
    {
        return $this->hasMany(Product::class, 'business_id', 'id')->where('is_del', 0)->field('id,title');
    }

    public static function getBusinessCart($id, $type = 1)
    {
        if ($type == 1) {
            $result = ProductCate::whereIn('id', $id)->column('title', 'id');
        } else {
            $result = ProductCate::whereIn('id', $id)->field('id,title')->select();
        }
        return $result;
    }


    public static function onAfterInsert($model)
    {
        //初始化默认账号
        $new = BusinessAdmin::create([
            'admin_name'  => $model->user->account,
            'password'    => $model->user->password,
            'mobile'      => $model->user->mobile,
            'role_id'     => 1,
            'business_id' => $model->id,
            'comment'     => '超级管理员'
        ]);
        Db::name('business_auth_group_access')->insert(['uid' => $new->id, 'group_id' => 1]);
    }

}
